package com.guess.lolguessing.interceptor;

import com.guess.lolguessing.constant.JwtClaimsConstant;
import com.guess.lolguessing.context.BaseContext;
import com.guess.lolguessing.porperties.JwtProperties;
import com.guess.lolguessing.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("当前线程" + Thread.currentThread().getId());
        //  检测当前拦截的是Controller的方法还是其他资源 如果不是动态方法 直接放行
        if(!(handler instanceof HandlerMethod)) {
            return true;
        }

        // 从请求头中获取令牌
        String token = request.getHeader("authorization");
        System.out.println(token);
        // 校验令牌
        try {
            log.info("jwt校验:{}", token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getKey(), token);
            System.out.println("???????" + claims.get(JwtClaimsConstant.USER_ID));
            Long empId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            System.out.println(empId);
            log.info("当前用户id:{}", empId);
            BaseContext.setCurrentId(empId);
            return true;
        } catch (Exception ex) {
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        BaseContext.removeCurrentId();
    }
}
